<template>
    <div class="menu-manage">
        <!-- 面包屑和标题 -->
        <el-breadcrumb separator="/" class="mb-2">
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>菜单管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="page-title">菜单管理</div>

        <!-- 查询区 -->
        <el-form :inline="true" :model="query" class="query-form">
            <el-form-item>
                <el-input v-model="query.displayName" placeholder="菜单名称" clearable style="width: 220px;" />
            </el-form-item>
            <el-form-item>
                <el-select v-model="query.category" placeholder="菜单类别" clearable style="width: 150px;">
                    <el-option label="系统管理" value="system" />
                    <el-option label="用户管理" value="user" />
                    <el-option label="菜单管理" value="menu" />
                    <el-option label="会议管理" value="meeting" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">查询</el-button>
                <el-button @click="onReset">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作区 -->
        <div class="toolbar mb-2">
            <el-button type="primary" @click="onAdd">新增菜单</el-button>
            <el-button @click="refreshMenu">刷新菜单</el-button>
        </div>

        <!-- 菜单表格 -->
        <el-table :data="tableData" border stripe style="width: 100%" row-key="PermissionId" ref="menuTableRef">
            <el-table-column prop="PermissionId" label="权限ID" min-width="80" />
            <el-table-column prop="DisplayName" label="菜单名称" min-width="150" />
            <el-table-column prop="Category" label="菜单类别" min-width="150" />
            <el-table-column prop="Pagepath" label="页面路径" min-width="200">
                <template #default="scope">
                    <span v-if="scope.row.Pagepath">{{ scope.row.Pagepath }}</span>
                    <el-tag v-else type="info" effect="plain">无页面路径</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="ParentId" label="父级ID" min-width="80">
                <template #default="scope">
                    <el-tag type="success" effect="plain">顶级菜单</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="240" fixed="right">
                <template #default="scope">
                    <el-button type="success" plain @click="onViewDetail(scope.row)">查看详情</el-button>
                    <el-button type="primary" plain @click="onAddChild(scope.row)">添加权限</el-button>
                    <el-button type="primary" plain @click="onEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" plain @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增菜单弹窗 -->
        <el-dialog v-model="addDialog.visible" :title="addDialog.title" width="500px">
            <el-form :model="menuFormData" label-width="100px" :rules="menuRules" ref="menuFormRef">
                <el-form-item label="菜单名称:" prop="DisplayName" required>
                    <el-input v-model="menuFormData.DisplayName" placeholder="请输入菜单名称" />
                </el-form-item>
                <el-form-item label="菜单类别:" prop="Category" required>
                    <el-input v-model="menuFormData.Category" placeholder="请输入菜单类别" />
                </el-form-item>
                <el-form-item label="页面路径:" prop="Pagepath">
                    <el-input v-model="menuFormData.Pagepath" placeholder="请输入页面路径" />
                </el-form-item>
                <el-form-item label="父级菜单:" prop="ParentId">
                    <el-select v-model="menuFormData.ParentId" placeholder="请选择父级菜单" style="width: 100%">
                        <el-option :value="0" label="顶级菜单" />
                        <el-option v-for="menu in parentMenuOptions" :key="menu.PermissionId" :label="menu.DisplayName"
                            :value="menu.PermissionId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="onSaveMenu">保存</el-button>
            </template>
        </el-dialog>

        <!-- 删除确认弹窗 -->
        <el-dialog v-model="deleteDialog.visible" title="删除确认" width="400px">
            <div>确定要删除菜单 <span class="text-danger">{{ deleteDialog.menuName }}</span> 吗？</div>
            <div class="mt-2">此操作将会同时删除该菜单下的所有子菜单，且不可恢复！</div>
            <template #footer>
                <el-button @click="deleteDialog.visible = false">取消</el-button>
                <el-button type="danger" @click="confirmDelete">确认删除</el-button>
            </template>
        </el-dialog>

        <!-- 菜单权限详情弹窗 -->
        <el-dialog v-model="detailDialog.visible" :title="`${detailDialog.menuName} 的权限详情`" width="80%">
            <div v-if="detailDialog.loading" class="dialog-loading">
                <el-icon class="is-loading">
                    <Loading />
                </el-icon>
                <span>正在加载权限数据...</span>
            </div>
            <div v-else>
                <el-table :data="detailDialog.permissions" border stripe style="width: 100%">
                    <el-table-column prop="PermissionId" label="权限ID" min-width="80" />
                    <el-table-column prop="DisplayName" label="权限名称" min-width="150" />
                    <el-table-column prop="Category" label="权限类别" min-width="150" />
                    <el-table-column prop="Pagepath" label="接口路径" min-width="200">
                        <template #default="scope">
                            <span v-if="scope.row.Pagepath">{{ scope.row.Pagepath }}</span>
                            <el-tag v-else type="info" effect="plain">无接口路径</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Type" label="权限类型" min-width="100">
                        <template #default="scope">
                            <el-tag v-if="scope.row.Type === 'button'" type="success">按钮权限</el-tag>
                            <el-tag v-else-if="scope.row.Type === 'api'" type="warning">API权限</el-tag>
                            <el-tag v-else type="info">其他权限</el-tag>
                        </template>
                    </el-table-column>
                </el-table>
                <div v-if="detailDialog.permissions.length === 0" class="empty-data">
                    <el-empty description="暂无权限数据" />
                </div>
            </div>
            <template #footer>
                <el-button @click="detailDialog.visible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMenuPermission, getMenuPermissionDetail } from '@/api/permission'
import { Loading } from '@element-plus/icons-vue'

// 定义菜单刷新事件，简单的全局事件总线
const MENU_REFRESH_EVENT = 'refresh-menu'
const emitMenuRefresh = () => {
    // 使用自定义事件通知菜单组件刷新
    window.dispatchEvent(new CustomEvent(MENU_REFRESH_EVENT))
}

// 菜单项接口
interface MenuPermissionItem {
    PermissionId: number;
    DisplayName: string;
    Category: string;
    Pagepath: string | null;
    ParentId: number;
    Children?: MenuPermissionItem[];
}

// 权限详情接口
interface PermissionDetail {
    PermissionId: number;
    DisplayName: string;
    Category: string;
    Pagepath: string | null;
    Type: string;
}

// 查询参数
const query = reactive({
    displayName: '',
    category: ''
})

// 表格数据
const tableData = ref<MenuPermissionItem[]>([])
const menuTableRef = ref()

// 表单数据
const menuFormData = reactive<MenuPermissionItem>({
    PermissionId: 0,
    DisplayName: '',
    Category: '',
    Pagepath: null,
    ParentId: 0
})

// 父级菜单选项
const parentMenuOptions = ref<MenuPermissionItem[]>([])

// 弹窗控制
const addDialog = reactive({
    visible: false,
    isEdit: false,
    parentId: 0,
    title: '新增菜单'
})

const deleteDialog = reactive({
    visible: false,
    menuId: 0,
    menuName: ''
})

// 权限详情弹窗控制
const detailDialog = reactive({
    visible: false,
    menuId: 0,
    menuName: '',
    loading: false,
    permissions: [] as PermissionDetail[]
})

// 表单校验规则
const menuRules = {
    DisplayName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    Category: [{ required: true, message: '请输入菜单类别', trigger: 'blur' }]
}

const menuFormRef = ref()

// 获取菜单数据
const fetchMenuData = async () => {
    try {
        const response = await getMenuPermission() as any

        // 处理响应数据
        const fullMenuData = response.Data || []
        console.log('获取到的完整菜单数据:', fullMenuData)

        // 只显示顶级菜单（ParentId为0的菜单项）
        tableData.value = fullMenuData.filter((item: MenuPermissionItem) => item.ParentId === 0)
        console.log('过滤后的一级菜单数据:', tableData.value)

        // 存储所有菜单项，用于父级菜单选择
        parentMenuOptions.value = fullMenuData.filter((item: MenuPermissionItem) =>
            // 只有顶级菜单可以作为父级菜单选项
            item.ParentId === 0
        )
        console.log('父级菜单选项:', parentMenuOptions.value)
    } catch (error: any) {
        console.error('获取菜单数据失败:', error)
        ElMessage.error(error.message || '获取菜单数据失败')
        tableData.value = []
    }
}

// 刷新菜单缓存
const refreshMenu = async () => {
    try {
        await fetchMenuData()
        // 通知菜单组件刷新
        emitMenuRefresh()
        ElMessage.success('菜单已刷新')
    } catch (error: any) {
        ElMessage.error('刷新菜单失败')
    }
}

// 搜索
const onSearch = () => {
    // 本地过滤逻辑
    if (!query.displayName && !query.category) {
        fetchMenuData()
        return
    }

    const displayNameLower = query.displayName.toLowerCase()
    const categoryLower = query.category.toLowerCase()

    fetchMenuData().then(() => {
        tableData.value = tableData.value.filter(menu => {
            const nameMatch = !displayNameLower || menu.DisplayName.toLowerCase().includes(displayNameLower)
            const categoryMatch = !categoryLower || (menu.Category && menu.Category.toLowerCase().includes(categoryLower))
            return nameMatch && categoryMatch
        })
    })
}

// 重置
const onReset = () => {
    query.displayName = ''
    query.category = ''
    fetchMenuData()
}

// 新增菜单
const onAdd = () => {
    // 重置表单
    menuFormData.PermissionId = 0
    menuFormData.DisplayName = ''
    menuFormData.Category = ''
    menuFormData.Pagepath = null
    menuFormData.ParentId = 0

    // 显示弹窗
    addDialog.isEdit = false
    addDialog.title = '新增菜单'
    addDialog.visible = true

    // 表单验证重置
    setTimeout(() => {
        menuFormRef.value?.clearValidate()
    }, 0)
}

// 添加子菜单
const onAddChild = (row: MenuPermissionItem) => {
    // 重置表单
    menuFormData.PermissionId = 0
    menuFormData.DisplayName = ''
    menuFormData.Category = row.Category || '' // 继承父菜单类别
    menuFormData.Pagepath = null
    menuFormData.ParentId = row.PermissionId

    // 显示弹窗
    addDialog.isEdit = false
    addDialog.visible = true

    // 修改对话框标题
    addDialog.title = `为 ${row.DisplayName} 添加权限按钮`

    // 表单验证重置
    setTimeout(() => {
        menuFormRef.value?.clearValidate()
    }, 0)
}

// 编辑菜单
const onEdit = (row: MenuPermissionItem) => {
    // 填充表单
    menuFormData.PermissionId = row.PermissionId
    menuFormData.DisplayName = row.DisplayName
    menuFormData.Category = row.Category
    menuFormData.Pagepath = row.Pagepath
    menuFormData.ParentId = row.ParentId

    // 显示弹窗
    addDialog.isEdit = true
    addDialog.title = `编辑菜单 - ${row.DisplayName}`
    addDialog.visible = true

    // 表单验证重置
    setTimeout(() => {
        menuFormRef.value?.clearValidate()
    }, 0)
}

// 删除菜单
const onDelete = (row: MenuPermissionItem) => {
    deleteDialog.menuId = row.PermissionId
    deleteDialog.menuName = row.DisplayName
    deleteDialog.visible = true
}

// 确认删除
const confirmDelete = () => {
    // 这里可以实现真实的删除逻辑
    ElMessage.success(`菜单 "${deleteDialog.menuName}" 删除成功`)
    deleteDialog.visible = false

    // 本地模拟删除
    tableData.value = tableData.value.filter(item => item.PermissionId !== deleteDialog.menuId)

    // 刷新菜单缓存
    refreshMenu()
}

// 保存菜单
const onSaveMenu = () => {
    if (!menuFormRef.value) return

    menuFormRef.value.validate((valid: boolean) => {
        if (!valid) {
            ElMessage.warning('请填写必填项')
            return
        }

        // 这里可以实现真实的保存逻辑
        if (addDialog.isEdit) {
            // 更新菜单
            ElMessage.success(`菜单 "${menuFormData.DisplayName}" 更新成功`)

            // 本地模拟更新
            const index = tableData.value.findIndex(item => item.PermissionId === menuFormData.PermissionId)
            if (index !== -1) {
                tableData.value[index] = { ...menuFormData }
            }
        } else {
            // 新增菜单
            const newMenu: MenuPermissionItem = {
                ...menuFormData,
                PermissionId: Date.now(), // 生成临时ID
                Children: []
            }

            // 如果是顶级菜单，直接添加到表格数据
            if (newMenu.ParentId === 0) {
                tableData.value.push(newMenu)
            } else {
                // 如果是子菜单，找到父菜单并添加
                fetchMenuData() // 重新获取完整菜单树
            }

            ElMessage.success(`菜单 "${menuFormData.DisplayName}" 创建成功`)
        }

        // 关闭弹窗
        addDialog.visible = false

        // 刷新菜单缓存
        refreshMenu()
    })
}

// 查看详情
const onViewDetail = async (row: MenuPermissionItem) => {
    detailDialog.menuId = row.PermissionId
    detailDialog.menuName = row.DisplayName
    detailDialog.permissions = []
    detailDialog.loading = true
    detailDialog.visible = true

    try {
        // 调用获取菜单权限详情接口
        const response = await getMenuPermissionDetail(row.PermissionId) as any

        detailDialog.permissions = response.Data
        console.log('获取到的权限详情:', detailDialog.permissions)
    } catch (error: any) {
        console.error('获取权限详情失败:', error)
        ElMessage.error(error.message || '获取权限详情失败')
        detailDialog.permissions = []
    } finally {
        detailDialog.loading = false
    }
}

// 组件挂载时加载数据
onMounted(fetchMenuData)
</script>

<style scoped>
.menu-manage {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    min-height: 600px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
    width: 100%;
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 12px;
}

.query-form {
    margin-bottom: 16px;
}

.toolbar {
    margin-bottom: 16px;
}

.mb-2 {
    margin-bottom: 12px;
}

.mb-4 {
    margin-bottom: 20px;
}

.mt-2 {
    margin-top: 12px;
}

.text-danger {
    color: #F56C6C;
    font-weight: bold;
}

.dialog-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    gap: 16px;
}

.empty-data {
    padding: 20px 0;
}
</style>
